package com.bluedot.www.core.utils;


import com.bluedot.www.core.service.BackupService;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;


/**
 * 线程池工具类
 *
 * @author Deng HongWei
 * @version 1.0
 * @date 2021/9/4 19:50
 */
public class ThreadUtil {

    /**
     * 线程池创建
     */
    private static final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
    /**
     * 获取数据备份的线程任务
     */
    private static ScheduledFuture runnableFutureBackUp = null;
    /**
     * 获取定时删除日志的线程任务
     */
    private static ScheduledFuture runnableFutureTimerDeletion = null;

    /**
     * 自动备份数据
     *
     * @param time 备份时间，三个时间分别为：7  15  30天
     * @return boolean
     * @author Deng HongWei
     * @date 2021/9/4 20:22
     */
    public static void autoBackUpUtil(Integer time) {
        if (runnableFutureBackUp != null) {
            runnableFutureBackUp.cancel(true);
        }
        runnableFutureBackUp = scheduledExecutorService.scheduleAtFixedRate(() -> {
            Object flag = BackupService.execute("handBackUp", new Object[]{"数据库自动备份"});
            System.out.println("自动备份是否执行成功：" + flag);
        }, 0, time, TimeUnit.DAYS);
    }

    /**
     * 定时删除数据库日志表数据
     *
     * @param time 定时删除，15天删一次
     * @return boolean
     * @author Ding YuXing
     * @date 2021/9/7 15:22
     */
    public static void timerDeletion(Integer time) {
        if (runnableFutureTimerDeletion != null) {
            runnableFutureTimerDeletion.cancel(true);
        }
        runnableFutureBackUp = scheduledExecutorService.scheduleAtFixedRate(() -> {
            try {
                Class LogClass = Class.forName("com.bluedot.www.core.service.LogService");
                Object o = LogClass.newInstance();
                Method timerDeletion = LogClass.getDeclaredMethod("timerDeletion", Integer.class);
                timerDeletion.setAccessible(true);
                Integer res = (Integer) timerDeletion.invoke(o, time);
                System.out.println("本次定时删除删除了" + res + "条数据");
            } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }, 0, time, TimeUnit.DAYS);
    }
}
